package com.crl.manager
{
	import flash.display.Stage;
	import flash.events.Event;
	import flash.utils.Timer;

	/**
	 * 渲染管理器; 
	 * @author crl
	 * 
	 */	
	public class RenderManager implements IRenderable
	{
		private var _stage:Stage;
		private var _timer:Timer;
		private var _queue:Vector.<IRenderable>;
		
		public function RenderManager()
		{
			_queue=new Vector.<IRenderable>();
		}
		
		public static var ins:RenderManager=new RenderManager();
		
		public function add(item:IRenderable):Boolean{
			if(_queue.indexOf(item) !=-1)return false;
			
			_queue.push(item);
			
			invalidate();
			return true;
		}
		
		public function invalidate():void{
			if(_stage==null){
				_timer.reset();
				_timer.start();
			}else{
				_stage.addEventListener(Event.RENDER,render,false,0,true);
			}
		}
		
		public function render(event:Event=null):void{
			if(_stage){
				_stage.removeEventListener(Event.RENDER,render);
			}
			
			var renderQueue:Vector.<IRenderable>=_queue.splice(0,_queue.length-1);
			
			for each(var item:IRenderable in renderQueue){
				item.render(event);
			}
		}
	}
}